


function on_global_cfg(data)
{
    if( data == null ){
        $('.global-cfg').text("暂无相关配置！")
    }
    else{
        var box =  $('.global-cfg')[0];
        box.innerHTML = '<div><strong>服务监听地址：</strong>'+data.addr+'</div>'
            + '<div><strong>服务监听端口：</strong>'+data.port+'</div>'
            + '<div><strong>线程数量：</strong>'+data.tasks+'</div>';
    }
}

/*
    It enables/disables the buttons of action by status
    status is a string, can be such values:
        standby, running, paused, error
    buttons are:
        开始, 暂停, 继续, 停止

Well done! You successfully read this important alert message.
*/
function on_status_changed(status)
{
    var btns = null;
    if( status == 'standby' ){
        btns = [true, false, false, false];
    }
    else if( status == 'running'){
        btns = [false, true, false, true];
    }
    else if( status == 'paused'){
        btns = [false, false, true, true];
    }
    else if( status == 'error'){
        btns = [true, false, false, false];
    }
    else{
        return;
    }
    $('.action .btn').each(function(idx, item, arr){
        if( btns[idx] ){
            item.removeAttribute('disabled');
        }
        else{
            item.setAttribute('disabled', 'disabled');
        }
    });
}

function on_flash(data){
    var alert_box = $('<div class="alert alert-'+data.category+'">'
    + '<button type="button" class="close" data-dismiss="alert">×</button>'
    + '</div>');
    alert_box.append(data.content);
    $('.jumbotron').parent().prepend(alert_box);
}

function refresh_echart(data){
    $.ajax({url:"/running/stat",success:function(result){
        console.log(result);
////
        var option = {
            xAxis: {
                    data: result.x
            },
            series: [
                {
                    data: result.queue
                },
                {
                    data: result.requests
                }
            ]
        };

        myChart.setOption(option);
////
    }});
}

var myChart = null;


function init_echart(){
    var dom = document.getElementById("echart");
    myChart = echarts.init(dom);

    var echart_data = {
        x: [],
        queue: [],
        requests:[]
    };

    var option = {
        title: {
            text: '负载、压力'
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data:['队列最大值','请求/分钟']
        },
        toolbox: {
            feature: {
                saveAsImage: {}
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: echart_data.x
        },
        yAxis: [
            {
                type: 'value',
                scale: true,
                name: '队列最大值',
                boundaryGap: [0, '100%'],
                splitLine: {
                    show: false
                }
            },
            {
                type: 'value',
                scale: true,
                name: '请求/分钟',
                boundaryGap: [0, '100%'],
                splitLine: {
                    show: false
                }
            }
        ],
        series: [
            {
                name: '队列最大值',
                type: 'line',
                yAxisIndex: 0,
                data: echart_data.queue
            },
            {
                name: '请求/分钟',
                type: 'line',
                yAxisIndex: 1,
                data: echart_data.requests
            }
        ]
    };

    if (option && typeof option === "object") {
        myChart.setOption(option, true);
    }
}

function init_status_list_for_backends(){
    $.ajax({url:"/running/health",success:function(result){
        console.log(result);
        var htmls = []
        for( s in result){
            htmls.push('<div class="memcached ');
            htmls.push(result[s][0]);
            htmls.push('" value="');
            htmls.push(s);
            htmls.push('">');
            htmls.push(s);
            desc = result[s][1].replace(/(^(\s+)|(\s)$)/g,"");
            if( desc.length > 0 ){
                htmls.push('<br>');
                htmls.push(desc);
            }
            htmls.push('</div>');
        }
        $("#backends").html(htmls.join(""));
        $('#backends').delegate('.memcached', 'click', on_click_backend);
    }});
}

function on_health_changed(data){
    var e = $('.memcached[value="'+data[0]+'"]')[0];
    e.setAttribute("class", "memcached "+data[1]);
}

$(document).ready(function() {
	console.log("index page");
	$('.action .btn').on('click', on_action_button_clicked);
	init_status_list_for_backends();
    init_echart();
    refresh_echart();
	var sock = io('/');
    sock.on('connect',
        function() {
            console.log("connect");
        });
    sock.on('disconnect',
        function(){
            sock.disconnect();
        });
    sock.on('global cfg', on_global_cfg);
    sock.on('status', on_status_changed);
    sock.on('echart',refresh_echart);
    sock.on('flash', on_flash);
    sock.on('health', on_health_changed)
} );



function on_action_button_clicked(e)
{
    if( e.target.innerText == '开始' ){
        window.location.href = '/running/form';
        return
    }

    if( e.target.innerText == '继续' ){
        $.get("/running/resume");
        return
    }

    if( e.target.innerText == '停止' ){
        var truthBeTold = window.confirm("终止代理服务器的运行？");
        if (truthBeTold) {
            $.get("/running/stop");
        }
        return;
    }

    if( e.target.innerText == '暂停' ){
        var truthBeTold = window.confirm("暂停代理服务器的运行？");
        if (truthBeTold) {
            $.get("/running/pause");
        }
        return;
    }
}

function on_click_backend(e){
    console.log(this.firstChild.wholeText);
    window.open("/log/list/?_flt_3_backend="+encodeURI(this.firstChild.wholeText), 'Log for bad');
}